<template>
  <main class="upload_avatar">
    <el-upload
      class="avatar-uploader"
      action="http://39.105.40.148:3001/users/uploadAvatar"
      :show-file-list="false"
      :on-success="uploadSuccess"
      :before-upload="uploadBefore"
      :data="{ token: token }"
      accept="image/*"
    >
      <img v-if="imgUrl" :src="imgUrl" class="avatar" />
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </main>
</template>

<script>
export default {
  name: "UploadAvatar",
  data() {
    return {
      imgUrl: "",
      path: "",
      token: window.sessionStorage.getItem("token"),
    };
  },
  methods: {
    uploadSuccess(res, file) {
      this.path = res.path;
      this.imgUrl = this.baseHttp + this.path;
    },
    //图片上传之前
    uploadBefore(file) {
      let limitMax = 5000 * 1024;
      if (file.size > limitMax) {
        this.$messageTips("大小超出限制");
        return false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.avatar-uploader {
  position: relative;
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border-radius: 50%;
  i {
    position: absolute;
    left: 0;
    top: 0;
    color: #409eff;
    display: none;
  }
}
.avatar-uploader:hover i {
  background: #000;
  opacity: 0.3;
  display: block;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>